package com.song.mall.seckill.scheduled;

import com.song.mall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author 宋超
 * HP - the login name of the current user.
 * 2021/10/17 - the current system date.
 * 20:22 - the current system time.
 *  //@Scheduled注解方式级别高于资源注入级别,导致资源注入失败.
 */

@Service
@Slf4j
public class SeckillSkuScheduled  {
    @Autowired
    SeckillService seckillService;
    @Autowired
    RedissonClient redissonClient;

    private  final String  upload_lock = "seckill:upload:lock";  //秒杀商品上架的分布式锁的名字

    //秒杀的幂等性处理，处理重复上架同个商品的问题用redis的分布式锁来解决

    //上架最近三天的秒杀商品
    @Scheduled(cron = "0 * * * * ?")  //每天晚上凌晨三点执行
    public void uploadSeckillSkuLatest3Days(){
        //1、重复上架就无需处理了
        log.info("上架秒杀的商品信息。。。。");
        //分布式锁,只要锁执行完成，状态已经更新完成，释放锁以后，其他人获取到就会拿到最新的一个状态，相当于保证了一个原子性
        //SeckillService seckillService = (SeckillService) TaskUtil.getBean("seckillService");
        //SeckillService seckillService = (SeckillService) this.getBean("seckillService");
        RLock lock = redissonClient.getLock(upload_lock);
        lock.lock(15, TimeUnit.SECONDS);
        try {
            seckillService.uploadSeckillSkuLatest3Days();
        }finally {
            lock.unlock();
        }
    }
}
